package cn.com.anypay.manager.miaoma.student.dto;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.ToString;
import lombok.EqualsAndHashCode;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;

/**
 * 学生响应DTO
 * 用于API响应，包含额外的计算字段和描述信息
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class StudentResponseDTO {

    // 继承StudentDTO的所有字段
    private Long id;
    private String studentNo;
    private String name;
    private Integer gender;
    private Integer age;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate birthDate;
    private String className;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate enrollDate;
    private Integer status;
    private String remark;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS", timezone = "GMT+8")
    private LocalDateTime createdTime;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS", timezone = "GMT+8")
    private LocalDateTime updatedTime;

    /**
     * 性别描述
     */
    private String genderDesc;

    /**
     * 状态描述
     */
    private String statusDesc;

    /**
     * 年龄段描述
     */
    private String ageGroupDesc;

    /**
     * 是否成年
     */
    private Boolean isAdult;

    /**
     * 在校时长（月数）
     */
    private Integer schoolDurationMonths;

    /**
     * 在校时长描述
     */
    private String schoolDurationDesc;

    /**
     * 账户状态（活跃、不活跃等）
     */
    private AccountStatus accountStatus;

    /**
     * 最后活跃时间（可以根据业务需求定义）
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private LocalDateTime lastActiveTime;

    /**
     * 头像URL（如果有的话）
     */
    private String avatarUrl;

    /**
     * 联系方式信息
     */
    private ContactInfo contactInfo;

    /**
     * 权限信息
     */
    private PermissionInfo permissions;

    /**
     * 账户状态枚举
     */
    public enum AccountStatus {
        ACTIVE("活跃"),
        INACTIVE("不活跃"),
        SUSPENDED("已暂停"),
        LOCKED("已锁定");

        private final String description;

        AccountStatus(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }
    }

    /**
     * 联系方式信息
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class ContactInfo {
        private String phone;
        private String email;
        private String emergencyContact;
        private String emergencyPhone;
        private String address;
    }

    /**
     * 权限信息
     */
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public static class PermissionInfo {
        /**
         * 是否可以编辑
         */
        private Boolean canEdit;

        /**
         * 是否可以删除
         */
        private Boolean canDelete;

        /**
         * 是否可以查看详情
         */
        private Boolean canView;

        /**
         * 是否可以修改状态
         */
        private Boolean canChangeStatus;

        /**
         * 自定义权限
         */
        private java.util.Set<String> customPermissions;
    }

    /**
     * 从基础StudentDTO创建响应DTO
     */
    public static StudentResponseDTO fromStudentDTO(StudentDTO studentDTO) {
        if (studentDTO == null) {
            return null;
        }

        StudentResponseDTO response = new StudentResponseDTO();
        // 复制基础字段
        response.setId(studentDTO.getId());
        response.setStudentNo(studentDTO.getStudentNo());
        response.setName(studentDTO.getName());
        response.setGender(studentDTO.getGender());
        response.setAge(studentDTO.getAge());
        response.setBirthDate(studentDTO.getBirthDate());
        response.setClassName(studentDTO.getClassName());
        response.setEnrollDate(studentDTO.getEnrollDate());
        response.setStatus(studentDTO.getStatus());
        response.setRemark(studentDTO.getRemark());
        response.setCreatedTime(studentDTO.getCreatedTime());
        response.setUpdatedTime(studentDTO.getUpdatedTime());

        // 计算描述字段
        response.setGenderDesc(response.calculateGenderDesc());
        response.setStatusDesc(response.calculateStatusDesc());
        response.setAgeGroupDesc(response.calculateAgeGroupDesc());
        response.setIsAdult(response.calculateIsAdult());
        response.setSchoolDurationMonths(response.calculateSchoolDuration());
        response.setSchoolDurationDesc(response.calculateSchoolDurationDesc());

        // 设置默认账户状态
        response.setAccountStatus(AccountStatus.ACTIVE);

        return response;
    }

    /**
     * 计算性别描述
     */
    private String calculateGenderDesc() {
        if (this.getGender() == null) {
            return "未知";
        }
        return switch (this.getGender()) {
            case 1 -> "男";
            case 2 -> "女";
            default -> "未知";
        };
    }

    /**
     * 计算状态描述
     */
    private String calculateStatusDesc() {
        if (this.getStatus() == null) {
            return "未知";
        }
        return switch (this.getStatus()) {
            case 0 -> "正常";
            case 1 -> "休学";
            case 2 -> "退学";
            default -> "未知";
        };
    }

    /**
     * 计算年龄段描述
     */
    private String calculateAgeGroupDesc() {
        if (this.getAge() == null) {
            return "未知";
        }
        int age = this.getAge();
        if (age < 6) return "学前";
        if (age < 12) return "小学";
        if (age < 15) return "初中";
        if (age < 18) return "高中";
        if (age < 22) return "大学";
        return "成人";
    }

    /**
     * 计算是否成年
     */
    private Boolean calculateIsAdult() {
        return this.getAge() != null && this.getAge() >= 18;
    }

    /**
     * 计算在校时长（月数）
     */
    private Integer calculateSchoolDuration() {
        if (this.getEnrollDate() == null) {
            return 0;
        }
        return Period.between(this.getEnrollDate(), LocalDate.now()).getMonths() +
               Period.between(this.getEnrollDate(), LocalDate.now()).getYears() * 12;
    }

    /**
     * 计算在校时长描述
     */
    private String calculateSchoolDurationDesc() {
        Integer months = calculateSchoolDuration();
        if (months == null || months == 0) {
            return "不足1个月";
        }

        int years = months / 12;
        int remainingMonths = months % 12;

        StringBuilder desc = new StringBuilder();
        if (years > 0) {
            desc.append(years).append("年");
        }
        if (remainingMonths > 0) {
            desc.append(remainingMonths).append("个月");
        }

        return desc.toString();
    }
}